package javacode.primary_class;

import javacode.secondary_class.ConvertString;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JOptionPane;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.ParsingException;

/**
 * Lop Xml tao 1 doi tuong load file xml vao tu dia chi cho truoc Lop nay co cac
 * ham convert de chuyen du lieu sang file excel
 */
public class Xml {

    public Document doc;                                                        
    public String path_doc;                                                     // duong dan toi file doc
    public ConvertString string;
    /**
     * ham xml co tham so url la dia chi cua file xml
     */
    public Xml(String url) throws ParsingException {
        ConvertString make = new ConvertString();
        // nhan file xml, convert, tra ve file xml tam   
        try {
            FileInputStream is = new FileInputStream(url);
            Scanner input = new Scanner(is, "UTF-8");                           // doc theo ma UTF-8
            String path_xml_tmp = make.getPath(url) + "~" + make.getFileNameFull(url);  // tao duong dan file tam co dia chi nhu file dua vao, ten + "~"
            path_doc = path_xml_tmp;
            FileOutputStream outp = new FileOutputStream(path_xml_tmp);
            PrintWriter output = new PrintWriter(outp, true);                   //auto flush
            // doc tep
            while (input.hasNextLine()) {
                String line = input.nextLine();
                output.println(line.replaceAll("&ldquo;", "“").replaceAll("&rdquo;", "”").replaceAll("&rdquo;", "”")
                                   .replaceAll("&ndash;", "-").replaceAll("&mdash;", "-"));
            }
            // dong cac luong doc ghi
            is.close();
            input.close();
            outp.close();
            output.close();
            // build Document cho lop xml
            FileReader file = new FileReader(path_xml_tmp);
            Builder build = new Builder();
            this.doc = build.build(file);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Đã có lỗi trong khi đọc file XML truyền vào");
            e.printStackTrace();
        }

    }
       /**
      * Ham convert cac truong trong file xml sang xls (7 cot)
      */
     public void convertToExcel(Excel ex) {
        int num_row_ex = 0;                                                     // tao bien chua vi tri dong trong sheet excel
        String retrieval = new String();                                        //bien chua retrieval
        String list_command = new String();                                     //bien chuoi chua cac command
        int nparamater = 0;
        int ncommand = 0;
        String in_put = new String();
        // lay nut goc
        Element root = this.doc.getRootElement();                               // so the description_topic
        Elements desciption_topics = root.getChildElements();                   // lay tat ca the con (<title> & <decsription>)
        for (int i = 1; i < desciption_topics.size(); i++) {                    // chay tu 1, bo the <title> dau tien
            Element des_topic = desciption_topics.get(i);                       // lay the desciption the chi so
            Elements blocks = des_topic.getChildElements();                     // lay ttat ca cac the con trong des_topic (<title> & <block>)  
            ncommand = 0;
            for (int j = 1; j < blocks.size(); j++) {                           // chay tu con thu nhat bo qua the <title>
                Element block = blocks.get(j);                                  // lay the <block> the chi so
                Element label = block.getFirstChildElement("label");            // lay the <label> dau tien cua <block>
                String name_block = label.getValue();
                Elements paras = null;
                Element para = null;
                if (name_block.startsWith("Commands")) {                        // neu dang o block chua Commands
                    paras = block.getChildElements();                           // lay tat ca cac the con (<para>)
                    for (int k = 1; k < paras.size(); k++) {                    // lap qua tat ca the <para> bat dau tu 1 bo the <label>
                        para = paras.get(k);
                        String command = para.getValue();
                        if (string.retrieval(command)) {                        // ham retriveal tra ve "true" neu command bat dau ban RTRV
                            retrieval = string.getRetrieval(command);           // neu no la ham retriveal
                        }
                        command = string.getCommand(command);                   
                        if (command != null) {
                            list_command += command + ":";
                            num_row_ex++;
                            ncommand++;
                            ex.WS.createRow(num_row_ex);
                            ex.WS.getRow(num_row_ex).createCell(0).setCellValue(command);
                        }
                    }
                }//ket thuc lay command va luu Retrieval

                if (name_block.startsWith("Descriptions")) {
                    paras = block.getChildElements();
                    int ndescription=0;
                    for (int p = 1; p < paras.size(); p++) {
                        para = paras.get(p);
                        String tmp = para.getValue();
                        String tmp_eq = string.getRetrieval(tmp);
                        if (list_command.indexOf(tmp_eq) >= 0) {
                            ndescription++;
                            tmp = string.getDescription(tmp);
                            ex.WS.getRow((num_row_ex - ncommand)+ ndescription).createCell(1).setCellValue(tmp);
                        }
                    }
                }
                if (name_block.startsWith("Input Format")) {                    //lay thang nao comamnd can sd
                    paras = block.getChildElements();
                    para = paras.get(1);
                    String tmp = para.getValue();
                    in_put = string.getParamaterRQ(tmp, list_command);
                    list_command = "";
                }
                if (name_block.startsWith("Parameters")) {
                    paras = block.getChildElements("subblock");
                    
                    for (int h = 0; h < paras.size(); h++) {
                        para = paras.get(h);
                        String tmp = para.getFirstChildElement("label").getValue();
                        if (in_put.indexOf(tmp) >= 0) {
                            nparamater ++;
                            Element para_ds = para.getFirstChildElement("para");
                            Element table = para.getFirstChildElement("table");
                            Element tgroup = table.getFirstChildElement("tgroup");
                            Element tbody = tgroup.getFirstChildElement("tbody");
                            Elements rows = tbody.getChildElements();
                            Element row2 = rows.get(1);
                            Elements nentry = row2.getChildElements();
                            String rs = "";
                            String tmp_rs = "";
                            if (nentry.size() > 1) {
                                Element tmp_entry = nentry.get(1);
                                Elements tmp_npara_entry = tmp_entry.getChildElements();
                                for (int q = 0; q < tmp_npara_entry.size(); q++) {

                                    Element para_entry = tmp_npara_entry.get(q);
                                    tmp_rs = para_entry.getValue();
                                    if (string.getEntry3(tmp_rs) == 1) {
                                        rs = tmp_rs;
                                    } else {
                                        rs = rs + " " + string.getEntry2(tmp_rs);
                                    }

                                }
                            } else {

                                rs = string.getEntry(nentry.get(0).getValue());
                            }
                            if (nparamater <= num_row_ex) {
                                ex.WS.getRow(nparamater).createCell(2).setCellValue(tmp);
                                ex.WS.getRow(nparamater).createCell(3).setCellValue(para.getFirstChildElement("para").getValue());
                                ex.WS.getRow(nparamater).createCell(4).setCellValue(rs);
                                ex.WS.getRow(nparamater).createCell(5).setCellValue(string.getDefault(para.getFirstChildElement("para").getValue()));
                                ex.WS.getRow(nparamater).createCell(6).setCellValue(retrieval);
                            } else {
                                num_row_ex++;
                                ex.WS.createRow(num_row_ex);                                
                                ex.WS.getRow(num_row_ex).createCell(2).setCellValue(tmp);
                                ex.WS.getRow(num_row_ex).createCell(3).setCellValue(para.getFirstChildElement("para").getValue());
                                ex.WS.getRow(num_row_ex).createCell(4).setCellValue(rs);
                                ex.WS.getRow(num_row_ex).createCell(5).setCellValue(string.getDefault(para.getFirstChildElement("para").getValue()));
                                ex.WS.getRow(num_row_ex).createCell(6).setCellValue(retrieval);            
                            }
                        }
                    }
                }

            } // kt lap bloc
        } // kt lap desciption_topic
     // kt convert
        File xml_tmp = new File(this.path_doc);
        xml_tmp.delete();
    }

     /**
      * Ham convert tat ca cac truong trong file xml sang xls (14 cot)
      */
    public void convertAllToExcel(Excel ex) {
        int num_row_ex = 0;                                                     // tao bien chua vi tri dong trong sheet excel
        String retrieval = new String();                                        //bien chua retrieval
        String list_command = new String();                                     //bien chuoi chua cac command
        int nparamater = 0;
        int ncommand = 0;
        int start = 1;
        String in_put = new String();
        // lay nut goc
        Element root = this.doc.getRootElement();                               // so the description_topic
        Elements desciption_topics = root.getChildElements();                   // lay tat ca the con (<title> & <decsription>)
        for (int i = 1; i < desciption_topics.size(); i++) {                    // chay tu 1, bo the <title> dau tien
            Element des_topic = desciption_topics.get(i);                       // lay the desciption the chi so
            Elements blocks = des_topic.getChildElements();                     // lay ttat ca cac the con trong des_topic (<title> & <block>)  
            ncommand = 0;
            for (int j = 1; j < blocks.size(); j++) {                           // chay tu con thu nhat bo qua the <title>
                Element block = blocks.get(j);                                  // lay the <block> the chi so
                Element label = block.getFirstChildElement("label");            // lay the <label> dau tien cua <block>
                String name_block = label.getValue();
                Elements paras = null;
                Element para = null;
                if (name_block.startsWith("Commands")) {                        // neu dang o block chua Commands
                    paras = block.getChildElements();                           // lay tat ca cac the con (<para>)
                    for (int k = 1; k < paras.size(); k++) {                    // lap qua tat ca the <para> bat dau tu 1 bo the <label>
                        para = paras.get(k);
                        String command = para.getValue();
                        if (string.retrieval(command)) {                        // ham retriveal tra ve "true" neu command bat dau ban RTRV
                            retrieval = string.getRetrieval(command);           // neu no la ham retriveal
                        }
                        command = string.getCommand(command);                   
                        if (command != null) {                                // thay yeu cau lay tat ca cac lenh nen khong can check nua (15/10)
                            list_command += command + ":";
                            num_row_ex++;
                            ncommand++;
                            ex.WS.createRow(num_row_ex);
                            ex.WS.getRow(num_row_ex).createCell(3).setCellValue(command);
                        }
                    }
                }//ket thuc lay command va luu Retrieval

                if (name_block.startsWith("Descriptions")) {
                    paras = block.getChildElements();
                    int ndescription=0;
                    for (int p = 1; p < paras.size(); p++) {
                        para = paras.get(p);
                        String tmp = para.getValue();
                        String tmp_eq = string.getRetrieval(tmp);
                        if (list_command.indexOf(tmp_eq) >= 0) {
                            ndescription++;
                            tmp = string.getDescription(tmp);
                            ex.WS.getRow((num_row_ex - ncommand)+ ndescription).createCell(4).setCellValue(tmp);
                        }
                    }
                }
                
                if (name_block.startsWith("Category")) {
                    paras = block.getChildElements();
                    para = paras.get(1);                                        // block nay chi co 2 con duy nhat, gia tri o con thu 2 
                    String tmp = para.getValue();
                    if (ncommand > 0)                                           // neu trong description_topic khong co ham command can lay thi khong in category
                        ex.WS.getRow((num_row_ex - ncommand + 1)).createCell(0).setCellValue(tmp);
                }
                
                if (name_block.startsWith("Security")) {
                    paras = block.getChildElements();
                    para = paras.get(1);                                        // block nay chi co 2 con duy nhat, gia tri o con thu 2 
                    String tmp = para.getValue();
                    if (ncommand > 0)                                           // neu trong description_topic khong co ham command can lay thi khong in security
                        ex.WS.getRow((num_row_ex - ncommand + 1)).createCell(1).setCellValue(tmp);
                }
                
                if (name_block.startsWith("Input Format")) {                    //lay thang nao comamnd can sd
                    paras = block.getChildElements();
                    para = paras.get(1);
                    String tmp = para.getValue();
                    String command = "";
                    int ninput = ncommand;
                    while(ninput > 0){
                       command = ex.WS.getRow(num_row_ex - ninput + 1).getCell(3).getStringCellValue();
                       command = string.getInputFormat(command, tmp);
                       ex.WS.getRow(num_row_ex - ninput + 1).createCell(5).setCellValue(command);
                       ninput--;
                    }
                    in_put = string.getParamaterRQ(tmp, list_command);
                    list_command = "";
                    start = num_row_ex - ncommand + 1;                           //  luu vi tri dau tien bat dau cua description_topic
                }
                if (name_block.startsWith("Parameters")) {
                    paras = block.getChildElements("subblock");
                    for (int h = 0; h < paras.size(); h++) {
                        para = paras.get(h);
                        String tmp = para.getFirstChildElement("label").getValue();
                        if (in_put.indexOf(tmp) >= 0) {
                            nparamater ++;
                            Element para_ds = para.getFirstChildElement("para");
                            Element table = para.getFirstChildElement("table");
                            Element tgroup = table.getFirstChildElement("tgroup");
                            Element tbody = tgroup.getFirstChildElement("tbody");
                            Elements rows = tbody.getChildElements();
                            Element row2 = rows.get(1);
                            Elements nentry = row2.getChildElements();
                            String rs = "";
                            String tmp_rs = "";
                            if (nentry.size() > 1) {
                                Element tmp_entry = nentry.get(1);
                                Elements tmp_npara_entry = tmp_entry.getChildElements();
                                for (int q = 0; q < tmp_npara_entry.size(); q++) {

                                    Element para_entry = tmp_npara_entry.get(q);
                                    tmp_rs = para_entry.getValue();
                                    if (string.getEntry3(tmp_rs) == 1) {
                                        rs = tmp_rs;
                                    } else {
                                        rs = rs + " " + string.getEntry2(tmp_rs);
                                    }

                                }
                            } else {

                                rs = string.getEntry(nentry.get(0).getValue());
                            }
                            if (nparamater <= num_row_ex) {
                                ex.WS.getRow(nparamater).createCell(6).setCellValue(tmp);// 
                                ex.WS.getRow(nparamater).createCell(7).setCellValue(para.getFirstChildElement("para").getValue());
                                ex.WS.getRow(nparamater).createCell(8).setCellValue(rs);
                                ex.WS.getRow(nparamater).createCell(9).setCellValue(string.getDefault(para.getFirstChildElement("para").getValue()));
                                ex.WS.getRow(nparamater).createCell(10).setCellValue(retrieval);
                            } else {
                                num_row_ex++;
                                ex.WS.createRow(num_row_ex);                                
                                ex.WS.getRow(num_row_ex).createCell(6).setCellValue(tmp);
                                ex.WS.getRow(num_row_ex).createCell(7).setCellValue(para.getFirstChildElement("para").getValue());
                                ex.WS.getRow(num_row_ex).createCell(8).setCellValue(rs);
                                ex.WS.getRow(num_row_ex).createCell(9).setCellValue(string.getDefault(para.getFirstChildElement("para").getValue()));
                                ex.WS.getRow(num_row_ex).createCell(10).setCellValue(retrieval);            
                            }
                        }
                    }
                }
               if (name_block.startsWith("Related Commands")) {
                    paras = block.getChildElements();
                    para = paras.get(1);                                        // block nay chi co 2 con duy nhat, gia tri o con thu 2 
                    String tmp = para.getValue();
                    if (ncommand > 0)                                         
                        ex.WS.getRow(start).createCell(2).setCellValue(tmp);
                }
            } // kt lap bloc
        } // kt lap desciption_topic
     // kt convert
        File xml_tmp = new File(this.path_doc);
        xml_tmp.delete();
    }
}